﻿using System;
using System.Linq;
using Evpo.ContactData.UI.Tools;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;
using Evpo.ContactData.ViewModel;

namespace Evpo.ContactData.UI.GeneralClasses
{
    public abstract class ItemList : System.Web.UI.UserControl
    {
        #region Constants
        private const string ListRepeaterName = "uiListView";
        #endregion Constants

        #region Handlers
        protected virtual void uiDataSource_Selecting(object sender, ObjectDataSourceSelectingEventArgs e)
        {
            e.InputParameters["model"] = BaseViewModel;
        }

        protected virtual void uiDeleteSelected_Click(object sender, EventArgs e)
        {
            DeleteSelected();
            RefreshList();
        }
        #endregion Handlers

        #region Fields
        protected ItemInListContainer _itemInListContainer = new ItemInListContainer();
        #endregion

        #region Properties

        protected abstract string ItemInListControlName
        {
            get;
        }

        protected abstract ListViewModel BaseViewModel
        {
            get;
        }

        protected abstract ListView ListView
        {
            get;
        }

        #endregion

        #region Methods

        internal void RefreshList()
        {
            ListView.DataBind();
        }

        protected void DeleteSelected()
        {
            foreach (int id in SelectedItems())
            {
                BaseViewModel.Delete(id);
            }
        }

        internal IEnumerable<int> SelectedItems()
        {
            foreach (int retVal in _itemInListContainer.SelectedItems(
                ListView.Items.Cast<Control>(), ItemInListControlName)
                )
                yield return retVal;
        }

        #endregion Methods
    }
}
